package com.haust.trade.service.impl;

import com.haust.commons.pojo.HaustResult;
import com.haust.dao.RedisDao;
import com.haust.pojo.TbOrder;
import com.haust.pojo.TbOrderItem;
import com.haust.pojo.TbOrderShipping;
import com.haust.pojo.TbUser;
import com.haust.rabbit.message.dto.HaustCreateOrderMessageBody;
import com.haust.rabbit.sender.MessageSender;
import com.haust.trade.service.TradeService;
import com.haust.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
public class TradeServiceImpl implements TradeService {

    @Value("${Haust.incr.order}")
    private String orderIncrKey;

    @Value("${Haust.incr.orderItem}")
    private String orderItemIncrKey;

    @Value("${Haust.trade.createOrder.exchange}")
    private String exchange;

    @Value("${Haust.trade.createOrder.routingKey}")
    private String routingKey;


    @Autowired
    private RedisDao redisDao;

    @Autowired
    private MessageSender messageSender;

    /**
     * 下订单：
     * 流程：
     * 1、数据完整性处理。如生产唯一主键
     * 2、发送异步消息RabbitMQ,通过消息消费者
     * 3、返回结果
     *
     * @param orderItems    订单项
     * @param orderShipping 订单物流，订单地址
     * @param order         订单
     * @param user          用户
     * @return
     */
    @Override
    public HaustResult goSettlement(String orderItems,
                                      TbOrderShipping orderShipping,
                                      TbOrder order,
                                      TbUser user,
                                      String token) {

        Date now = new Date();

        //1、补充订单数据
        Long orderId = null;
        try {
            orderId = redisDao.incr(orderIncrKey);
        } catch (Exception e) {
            e.printStackTrace();
            return HaustResult.error("服务忙，请稍后！");
        }
        order.setOrderId(orderId);
        order.setBuyerNick(user.getUsername());
        order.setCreateTime(now);
        order.setStatus(1);
        order.setUserId(user.getId());

        //2、补充物流信息
        orderShipping.setOrderId(orderId);
        orderShipping.setCreated(now);


        //3、补充订单项数据

        List<TbOrderItem> tbOrderItems = JsonUtils.jsonToList(orderItems, TbOrderItem.class);

        if (tbOrderItems == null) {
            return HaustResult.error("服务忙，请稍后！");
        }


        for (TbOrderItem item : tbOrderItems) {
            Long orderItemIncr = null;
            try {
                orderItemIncr = redisDao.incr(orderItemIncrKey);
            } catch (Exception e) {
                return HaustResult.error("服务忙，清稍后！");
            }

            item.setId(orderItemIncr);
            item.setOrderId(orderId);
        }

        HaustCreateOrderMessageBody messageBody =
                new HaustCreateOrderMessageBody();

        messageBody.setTbOrder(order);
        messageBody.setTbOrderItem(tbOrderItems);
        messageBody.setTbOrderShipping(orderShipping);
        messageBody.setTbUser(user);
        messageBody.setToken(token);

        messageSender.sendMessage(exchange, routingKey, messageBody);

        return HaustResult.ok(orderId);
    }
}
